import time

import jwt
from jwt import DecodeError

from user.models import User

key = "ISnsiidhsfoiagsdfoiabsdfoiasgbdoilashbdoiaslbnd"  # 秘钥
TOKEN_TIME = 3600 * 24 * 3  # token默认3天过期
jwt_header = {
    "alg": "HS256",
    "typ": "JWT"
}


class userValidate:
    @staticmethod
    def check(token):
        """
        判断 token 是否正确
        """

        try:
            payload: dict = jwt.decode(token, key, True)
            print(payload)
            username = payload.get('username')
        except DecodeError as e:
            return None
        except jwt.exceptions.ExpiredSignatureError:
            return None
        if time.time() < payload.get("exp"):
            return User.objects.get(username=username)
        return None

    @staticmethod
    def make_token(username, overdue_time=3600) -> str:
        """
        用户的token返回
        """
        return jwt.encode(
            payload={
                "username": username,
                "exp": time.time() + TOKEN_TIME
            },
            headers=jwt_header,
            algorithm='HS256',
            key=key,
        ).decode()
